package yams.task;

import com.alibaba.fastjson.JSONObject;
import com.vdurmont.emoji.EmojiParser;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import yams.domain.UserEntity;
import yams.service.IUserService;
import yams.utils.WeixinUtil;

import javax.annotation.Resource;
import java.io.*;
import java.util.List;
import java.util.Objects;
import static yams.utils.WeixinUtil.USER_INFO_URL;


@Component
public class UserTask {
    private final static Logger logger = LoggerFactory.getLogger(UserTask.class);
    @Resource
    private IUserService userService;

    @Scheduled(cron = "0 0 19 * * ?")
    public void execute() {
        //查找所有openid有值的用户
        UserEntity condition = new UserEntity();
        condition.getProperties().put("weChat_is_not_empty", "0");
        condition.getProperties().put("nickname_is_empty", "0");
        List <UserEntity> users = userService.listAll(condition);

        users.forEach(userEntity -> {
            try {
                String nickName = queryWechatInfo(userEntity.getWeChat());
                if (!StringUtils.isEmpty(nickName)) {
                    nickName = EmojiParser.parseToAliases(nickName);
                    userEntity.setNickname(nickName);
                    userService.saveInfo(userEntity);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 获取微信昵称
     * @param openId
     * @throws IOException
     */
    public String queryWechatInfo(String openId) throws IOException {

        String result = "";
        String token = WeixinUtil.getAccessToken();

        String requestUrl = WeixinUtil.USER_INFO_URL + "?access_token=" + token + "&openid=" + openId + "&lang=zh_CN";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(requestUrl);
        CloseableHttpResponse response = httpclient.execute(httpGet);

        try {
            HttpEntity resEntity = response.getEntity();
            InputStream resIs = resEntity.getContent();
            InputStreamReader inputStreamReader = new InputStreamReader(resIs, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuffer buffer = new StringBuffer();
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            resIs.close();
            JSONObject jsonObject = JSONObject.parseObject(buffer.toString());
            if (jsonObject.get("errcode") != null && Objects.equals(jsonObject.get("errcode").toString(), "40013")) {
                WeixinUtil.TOKEN_CACHE_TOKEN_TIME = 0L;
            } else {
                if (jsonObject.get("subscribe") != null && Integer.parseInt(jsonObject.get("subscribe").toString()) > 0)
                    result = jsonObject.get("nickname").toString();
            }

            EntityUtils.consume(resEntity);
            return result;
        } finally {
            response.close();
        }

    }

}
